package com.woniu.microchargeserver.chargemag.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.woniu.microchargeserver.chargemag.service.IChargedItemsService;
import com.woniu.microchargeserver.chargemag.service.IRoomAdvanceDepositService;
import com.woniu.microchargeserver.chargemag.service.IRoomChargeService;
import com.woniu.microchargeserver.common.bean.dtobean.RoomChargeDto;
import com.woniu.microchargeserver.common.bean.dtobean.RoomChargeProDto;
import com.woniu.microchargeserver.common.bean.dtobean.TollDto;
import com.woniu.microchargeserver.common.util.TraceUtil;
import com.woniu.microcommonsserver.entity.ChargedItemsInfoEntity;
import com.woniu.microcommonsserver.entity.RoomChargedItemsInfoEntity;
import com.woniu.microcommonsserver.entity.SpaceInfoEntity;
import com.woniu.microcommonsserver.param.ResponseMsg;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

/**
 * @author: hejie
 * @date: 2021/1/25 9:32
 * @description:
 */
@RestController
@RequestMapping("/roomCharge")
public class RoomChargeController {

    @Resource
    private IRoomChargeService roomChargeServiceImpl;
    @Resource
    private IChargedItemsService chargedItemsServiceImpl;
    @Resource
    private IRoomAdvanceDepositService roomAdvanceDepositService;


    /**查询该房间的  房间名字、业主、所有收费项目
     * 查询所有的 房间（就是房间的List）：List<SpaceInfoEntity>
     * 根据“build_info中的id”查询属于该build的所有building下的所有房间(如“水青花都小区-11号楼-5单元-8层-802”，即rank为4的SpaceInfoEntity)
     * 如3号楼
     * @author hejie
     * @param bId：build_info中的id  ，小区的id
     * @param buildingId 楼栋的id
     * @param buildingAbbreviation 楼栋名字：如3号楼(自己根据楼栋id去查询：impl中)
     * @param roomName 房间的名字（在前端传入的是 “3-5-1002”，impl处需要 把它转为“xxx小区-3号楼-5单元-10层-1002”）
     * @param ownerName 业主名字
     * @return
     */
    @GetMapping(value="/findRoomsByParams", produces = {"application/json;charset=utf-8"})
    public ResponseMsg findRoomsByParams(Long bId,
                                         Long buildingId,
                                         String buildingAbbreviation,
                                         String roomName,
                                         String ownerName){
        List<RoomChargeProDto> rcps = roomChargeServiceImpl.findRoomsByParams( bId,
                                         buildingId,
                                         roomName,
                                         ownerName);
        return new ResponseMsg(200, "查询成功", rcps);
    }



    /**
     * 新增 一个收费项目、房间的中间表
     * @author hejie
     * @param ids:根据 房间、收费项目中间表的id：删除一个中间表的记录
     * @return
     */
    @DeleteMapping(value="/del", produces = {"application/json;charset=utf-8"})
    public ResponseMsg delRoomCharge(@RequestBody Long[] ids){
        System.out.println("\n"+"\tids="+ Arrays.toString(ids) +TraceUtil.positionTrace());

        ResponseMsg responseMsg = new ResponseMsg(200,"删除成功",null);
        for ( Long id:ids) {
            roomChargeServiceImpl.delRoomCharge( id);
        }
        return responseMsg;
    }

    /**
     * 新增 一个收费项目、房间的中间表
     * @author hejie
     * @param chargedItemsInfoId  收费项目外键id
     * @param currentRoomId  房间外键id：用户当前点击的房间的id
     *                       注意：impl中根据“收费项目”中的“周期单位”自己设置“开始计费时间和结束计费时间”
     * @return
     */
    @PostMapping(value="/more",produces = {"application/json;charset=utf-8"})
    public ResponseMsg addRoomCharge(Long currentRoomId,Long chargedItemsInfoId){
        System.out.println("\n"+"\tcurrentRoomId="+currentRoomId+"\tchargedItemsInfoId="+chargedItemsInfoId+TraceUtil.positionTrace());

        ResponseMsg responseMsg = new ResponseMsg(200,"新增成功",null);
        roomChargeServiceImpl.addRoomCharge( currentRoomId, chargedItemsInfoId);

        return responseMsg;
    }

    /**
     * 分批收款： 修改 一个收费项目、房间的中间表
     * @author hejie
     * @return
     */
    @PutMapping(value="/partialCollectionUpdate",produces = {"application/json;charset=utf-8"})
    public ResponseMsg partialCollectionUpdate(@RequestBody TollDto tollDto){
        System.out.println("\n"+"\ttollDto="+tollDto+TraceUtil.positionTrace());
        //提取和修改“房间、收费项目中间表”
        RoomChargedItemsInfoEntity roomChargedItemsInfoEntity= tollDto.getRoomChargedItemsInfoEntity();
        roomChargeServiceImpl.update(roomChargedItemsInfoEntity);
        ResponseMsg responseMsg = new ResponseMsg(200,"修改成功",null);

        return responseMsg;
    }

    /**
     * 收费，就是修改 一个收费项目、房间的中间表
     * @author hejie
     * @TollDto:
     * @roomChargedItemsInfoEntity 房间收费中间表
//     * @param advanceReceiptBalance 预收款余额（这里传-1时，后端不修改“预收款余额”；否则，后端要修改“预收款余额”）
     * @return
     */
    @PutMapping(value="/tollUpdate",produces = {"application/json;charset=utf-8"})
    public ResponseMsg tollUpdate(@RequestBody TollDto tollDto){
        System.out.println("\n"+"\ttollDto="+tollDto+TraceUtil.positionTrace());

        ResponseMsg responseMsg = new ResponseMsg(200,"修改成功",null);

        //提取和修改“房间、收费项目中间表”
        RoomChargedItemsInfoEntity roomChargedItemsInfoEntity= tollDto.getRoomChargedItemsInfoEntity();
        //'是否完成支付（自己定义的）。1-完成支付，2-未支付',
        roomChargedItemsInfoEntity.setCompletePaymentStatus((byte)1);
        roomChargeServiceImpl.update(roomChargedItemsInfoEntity);
        //修改 该房间的 “预收金余额”：情况1 看前端传回来的 预交抵扣了多少； 零钱是否转为 预交金 （后者-前者 是“该房间的预交金增量”——一个房间只维护一个预交金记录：加加减减）
        //看此次收费，原剩余的预收金被 抵扣了多少，给prepaidDeduction
        Double prepaidDeduction=roomChargedItemsInfoEntity.getPrepaidDeduction();
        //获取 零钱选项。1-退补，2-转预存
        Byte changeOptions =roomChargedItemsInfoEntity.getChangeOptions();
        Double remainMoneyIncrement=0.0;
        if (changeOptions==2){
            //获取“转预存的零钱”
            remainMoneyIncrement=roomChargedItemsInfoEntity.getChangeMakeUp();
        }
        //减去被 抵扣的
        remainMoneyIncrement = remainMoneyIncrement - roomChargedItemsInfoEntity.getPrepaidDeduction();
        roomAdvanceDepositService.updateAdvanceDepositByRid(tollDto.getRoomId(), remainMoneyIncrement);

        return responseMsg;
    }

    /**
     * 修改 一个收费项目、房间的中间表
     * @author hejie
     * @return
     */
    @PutMapping(value="/update",produces = {"application/json;charset=utf-8"})
    public ResponseMsg updateAdmin(@RequestBody RoomChargeDto roomChargeDto){
        System.out.println("\n"+"\troomChargeDto="+roomChargeDto+TraceUtil.positionTrace());

        ResponseMsg responseMsg = new ResponseMsg(200,"修改成功",null);

        //提取和修改“收费项目”
        ChargedItemsInfoEntity chargedItemsInfoEntity=  roomChargeDto.getChargedItemsInfoEntity();
        chargedItemsServiceImpl.updateChargedItems(chargedItemsInfoEntity);
        //提取和修改“房间、收费项目中间表”
        RoomChargedItemsInfoEntity roomChargedItemsInfoEntity= roomChargeDto.getRoomChargedItemsInfoEntity();
        roomChargeServiceImpl.update(roomChargedItemsInfoEntity);

        return responseMsg;
    }

    /**
     * 分页查询数据:通过房间id查询 该房间的收费项目
     *  现在不需要调用别人的微服务了哦----还没有写完：目前查询了收费项目和 中间表的信息，房间的信息还没有查： 在impl中还要去根据 roomId去查询房间信息；然后把房间信息放到 本微服务mapper查询回来的List中（比如用set方法）
     * @author hejie
     * @param pageNum 第几页
     * @param pageSize 每页显示多少条数据
     * @param column 排序的字段
     * @param order 升序还是降序
     * @param roomId 房间的id（rank为4的SpaceInfoEntity）
     * @param roomName 页面上显示的房间名字（它不去数据库参与查询，而是直接在impl中赋值），如3-5-1002（指3号楼-5栋-10层-02号）
     * @return
     */
    @RequestMapping(value="/findRoomChargeItemByRoomId",produces = {"application/json;charset=utf-8"})
    public ResponseMsg findRoomChargeItemByRoomId(@RequestParam(required = false,defaultValue = "1") int pageNum,
                                                  @RequestParam(required = false,defaultValue = "5")int pageSize,
                                                  String column,
                                                  String order,
                                                  Long roomId,
                                                  String roomName){
        System.out.println("\nroomId="+roomId+"\tpageNum="+pageNum+"\tpageSize="+pageSize+ TraceUtil.positionTrace());

        PageInfo<RoomChargeDto> page = roomChargeServiceImpl.findRoomChargeItemByRoomId(pageNum,pageSize,column,order, roomId, roomName);
        System.out.println("page.getPageNum()="+page.getPageNum());
        System.out.println("page.getPageSize()="+page.getPageSize());
        System.out.println("page.getTotal()="+page.getTotal());
        System.out.println("page.getList()="+page.getList());
        return new ResponseMsg(200,"查询成功",page);
    }

}
